//
//  QYTreeHoleVC.swift
//  QingYuJSQ
//
//  Created by 李东 on 2024/4/4.
//

import UIKit
import FSCalendar
import SnapKit

class QYTreeHoleVC: QYBaseVC {
    lazy var yearMonthView = UIView()
    lazy var yearLabel = UILabel()
    lazy var monthLabel = UILabel()
    lazy var calendarBgView = UIView()
    lazy var calender = FSCalendar()
    lazy var addBtn = UIButton(type: .custom)
    
    var currentDate: Date!
    lazy var dataList = [QYDataModel]()

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "树洞"
        initUI()
        currentDate = calender.today ?? Date()
        NotificationCenter.default.addObserver(self, selector: #selector(reloadHandle), name: .DataDidChangedNoti, object: nil)

    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        dataList = QYDataHelper.shared.getLocalList(isRefresh: true)
        calender.reloadData()
    }

    
    @objc func reloadHandle() {
        dataList = QYDataHelper.shared.getLocalList(isRefresh: true)
        calender.reloadData()
    }
    
    lazy var df: DateFormatter = {
        let temp = DateFormatter()
        temp.locale = Locale(identifier: "zh_CN")
        // 设置日期格式，yyyy表示年份，MMMM表示中文大写的月份
        temp.dateFormat = "yyyy年 MMMM"
        return temp
    }()
    
    lazy var df1: DateFormatter = {
        let temp = DateFormatter()
        temp.locale = Locale(identifier: "zh_CN")
        // 设置日期格式，yyyy表示年份，MMMM表示中文大写的月份
        temp.dateFormat = "MMMM"
        return temp
    }()

    lazy var df2: DateFormatter = {
        let temp = DateFormatter()
        temp.dateFormat = "yyyyMMdd"
        return temp
    }()

    func initUI()  {
        let list = df.string(from: Date()).components(separatedBy: " ")
        
        yearMonthView.isUserInteractionEnabled = true
        yearMonthView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showMonthDataHandle)))
        view.addSubview(yearMonthView)
        yearMonthView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalTo(40)
            make.width.equalTo(200)
        }
        
        yearLabel.textColor = .white
        yearLabel.font = UIFont.Semibold(ofSize: 24)
        yearLabel.text = list[0]
        yearMonthView.addSubview(yearLabel)
        yearLabel.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.top.equalToSuperview()
        }
        
        monthLabel.textColor = .white
        monthLabel.font = UIFont.systemFont(ofSize: 16)
        monthLabel.text = list[1]
        yearMonthView.addSubview(monthLabel)
        monthLabel.snp.makeConstraints { make in
            make.left.equalTo(yearLabel)
            make.top.equalTo(yearLabel.snp.bottom).offset(20)
            make.bottom.equalToSuperview()
        }
        
        calendarBgView.backgroundColor = .white
        calendarBgView.layer.cornerRadius = 15
        calendarBgView.layer.masksToBounds = true
        view.addSubview(calendarBgView)
        calendarBgView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(monthLabel.snp.bottom).offset(20)
            make.height.equalTo(380)
        }
        
        calender.placeholderType = .none
        calender.delegate = self
        calender.dataSource = self
        calender.headerHeight = 0
        calender.weekdayHeight = 40
        calender.allowsMultipleSelection = false
//        calender.firstWeekday = 2
        calender.rowHeight = 40
        calender.appearance.weekdayFont = UIFont.systemFont(ofSize: 12)
        calender.appearance.weekdayTextColor = .black
        calender.appearance.titleFont = UIFont.systemFont(ofSize: 14)
        calender.appearance.titleDefaultColor = .black
        calender.appearance.todayColor = .init(hex: 0xFD4D95)
        calender.appearance.titleTodayColor = .white
        calender.locale = Locale.init(identifier: "zh_CN")
        calender.appearance.caseOptions = .weekdayUsesSingleUpperCase
        calender.register(QYDateCell.self, forCellReuseIdentifier: QYDateCell.CellID)
        calendarBgView.addSubview(calender)
        calender.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.bottom.equalToSuperview()
        }
        
        addBtn.setImage(UIImage(named: "icon_add"), for: .normal)
        addBtn.addTarget(self, action: #selector(addHandle), for: .touchUpInside)
        view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-50)
        }
    }
    
    @objc func addHandle() {
        let vc = QYSelectEmotionVC(selectDate: currentDate)
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true)
    }
    
    @objc func showMonthDataHandle() {
        navigationController?.pushViewController(QYHoleListVC(currentMonth: calender.currentPage), animated: true)
    }
}

extension QYTreeHoleVC: FSCalendarDelegate, FSCalendarDataSource, FSCalendarDelegateAppearance {
    //日期cell被选中
    func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
        currentDate = date
        let dateStr1 = df2.string(from: date)
        let ts = Int(df2.date(from: dateStr1)!.timeIntervalSince1970)
        if let tempModel = dataList.first(where: {$0.ts == ts}) {
            let vc = QYEmotionDetailVC(model: tempModel, selectDate: date)
            vc.modalPresentationStyle = .fullScreen
            present(vc, animated: true)
        }
    }
    
    //月份page发生改变
    func calendarCurrentPageDidChange(_ calendar: FSCalendar) {
        monthLabel.text = df1.string(from: calendar.currentPage)
    }
    
//    func maximumDate(for calendar: FSCalendar) -> Date {
//        Date()
//    }
    
    //使用自定义cell
    func calendar(_ calendar: FSCalendar, cellFor date: Date, at position: FSCalendarMonthPosition) -> FSCalendarCell {
        let cell =  calendar.dequeueReusableCell(withIdentifier: QYDateCell.CellID, for: date, at: position)
        if let tempCell = cell as? QYDateCell {//判断当前日期是否有数据
            let dateStr1 = df2.string(from: date)
            let ts = Int(df2.date(from: dateStr1)!.timeIntervalSince1970)
            if let tempModel = dataList.first(where: {$0.ts == ts}) {
                tempCell.img = UIImage(named: tempModel.emotion)
            }else{
                tempCell.img = nil
            }
        }
        return cell
    }
    
    //cell即将显示
    func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at monthPosition: FSCalendarMonthPosition) {
        if cell.dateIsToday {
            cell.titleLabel.text = "今"
            cell.titleLabel.textColor = .white
        }else{
            cell.titleLabel.textColor = .black
        }
    }

    //未来日期不可交互、非当前page月份的日期不可选中
    func calendar(_ calendar: FSCalendar, shouldSelect date: Date, at monthPosition: FSCalendarMonthPosition) -> Bool {
//        let day = calendar.gregorian.dateComponents([.day], from: calendar.formatter.date(from: calendar.formatter.string(from: Date()))!, to: date).day ?? 0
//        let m1 = calendar.gregorian.component(.month, from: date)
//        let m2 = calendar.gregorian.component(.month, from: calendar.currentPage )
//        return day <= 0 && m1 == m2
        
//        let str = dateFormatter2.string(from: date)
//        guard let mm = LXTYQBirthdayHelper.shared.getLocalList().first(where: {$0.ts == Int(dateFormatter2.date(from: str)!.timeIntervalSince1970)})  else { return false}
        return true
    }
    
    //选中时的背景颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillSelectionColorFor date: Date) -> UIColor? {
        return .init(hex: 0xFD4D95)
    }
    
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, fillDefaultColorFor date: Date) -> UIColor? {
        if calendar.today == date {
            return .init(hex: 0xFD4D95)
        }
        return .init(hex: 0xF1F3F7)
    }
    
    //选中时的日期颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleSelectionColorFor date: Date) -> UIColor? {
        return .init(hex: 0xF1F3F7)
    }
    
    //默认的日期颜色
    func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) -> UIColor? {
//        let day = calendar.gregorian.dateComponents([.day], from: calendar.formatter.date(from: calendar.formatter.string(from: Date()))!, to: date).day ?? 0
//        if day > 0  {//未来日期
//            return .white.withAlphaComponent(0.4)
//        }
//        if calendar.gregorian.isDateInToday(date)  {
//            return .black
//        }
//        let tt = Int(dateFormatter2.date(from: dateFormatter2.string(from: date))!.timeIntervalSince1970)
//        if let mm = ZHNoteManager.shared.notes.first(where: {$0.timestamp == tt}) {
//            return .black
//        }
        return .black
    }
    
    
 
}
